/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aybolit.core.security;

/**
 *
 * @author Masumov Emin
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

public class AuthManager implements AuthenticationManager {

    // Our custom DAO layer
   
    // We need an Md5 encoder since our passwords in the database are Md5 encoded. 
    private Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();

    @Override
    public Authentication authenticate(Authentication auth)
            throws AuthenticationException {


        // Init a database user object
      

            // Retrieve user details from database

        // Compare passwords
        // Make sure to encode the password first before comparing

        // Here's the main logic of this custom authentication manager
        // Username and password must be the same to authenticate
       
            return new UsernamePasswordAuthenticationToken(
                    auth.getName(),
                    auth.getCredentials(),
                    getAuthorities(0));
        
    }

    /**
     * Retrieves the correct ROLE type depending on the access level, where
     * access level is an Integer. Basically, this interprets the access value
     * whether it's for a regular user or admin.
     *
     * @param access an integer value representing the access of the user
     * @return collection of granted authorities
     */
    public Collection<GrantedAuthority> getAuthorities(int access) {
        // Create a list of grants for this user
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

        // All users are granted with ROLE_USER access
        // Therefore this user gets a ROLE_USER by default
        authList.add(new GrantedAuthorityImpl("ROLE_USER"));
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!");
        // Check if this user has admin access 
        // We interpret Integer(1) as an admin user
        if (access== 1) {
            // User has admin access
            authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
        }

        // Return list of granted authorities
        return authList;
    }
}